/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package XML;

import Object.Torrent;
import java.io.IOException;
import java.io.File;

import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.DocumentBuilder;

import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerException;
import javax.xml.transform.Source;
import javax.xml.transform.dom.DOMSource;
import javax.xml.transform.Result;
import javax.xml.transform.stream.StreamResult;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerFactory;

import org.xml.sax.SAXParseException;
import org.xml.sax.SAXException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;

/**
 *
 * @author QuangHau
 */
public class DOMUtil {

    public synchronized static Document parse(String fileName) {
        Document document = null;
        // Initiate DocumentBuilderFactory
        DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();

        // To get a validating parser
        factory.setValidating(false);
        // To get one that understands namespaces
        factory.setNamespaceAware(true);

        try {
            // Get DocumentBuilder
            DocumentBuilder builder = factory.newDocumentBuilder();
            // Parse and load into memory the Document
            document = builder.parse(new File(fileName));
            return document;

        } catch (SAXParseException spe) {
            // Error generated by the parser
            System.out.println("\n** Parsing error , line " + spe.getLineNumber()
                    + ", uri " + spe.getSystemId());
            System.out.println(" " + spe.getMessage());
            // Use the contained exception, if any
            Exception x = spe;
            if (spe.getException() != null) {
                x = spe.getException();
            }
            x.printStackTrace();
        } catch (SAXException sxe) {
            // Error generated during parsing
            Exception x = sxe;
            if (sxe.getException() != null) {
                x = sxe.getException();
            }
            x.printStackTrace();
        } catch (ParserConfigurationException pce) {
            // Parser with specified options can't be built
            pce.printStackTrace();
        } catch (IOException ioe) {
            // I/O error
            ioe.printStackTrace();
        }
        return null;
    }
    
    public synchronized static void writeXmlToFile(String filename, Document document) {
        try {
            // Prepare the DOM document for writing
            Source source = new DOMSource(document);

            // Prepare the output file
            File file = new File(filename);
            Result result = new StreamResult(file);

            // Write the DOM document to the file
            // Get Transformer
            Transformer xformer = TransformerFactory.newInstance().newTransformer();
            // Write to a file
            xformer.transform(source, result);
        } catch (TransformerConfigurationException e) {
            System.out.println("TransformerConfigurationException: " + e);
        } catch (TransformerException e) {
            System.out.println("TransformerException: " + e);
        }
    }

    public static void insertChunk(Torrent torrenFile, String idChunk) {
        Document document = DOMUtil.parse("Data.xml");
        NodeList listFile = document.getDocumentElement().getChildNodes();
        String  idFile = torrenFile.getId();
        int i;
        for (i = 0; i < listFile.getLength(); i++) {
            Node nodeFile = listFile.item(i);
            if (nodeFile.getNodeName().equals("File") && nodeFile.getAttributes().getNamedItem("id").getNodeValue().equals(idFile)) {
                //fle da co, inser chunk
                NodeList listChunk = nodeFile.getChildNodes();
                int j;
                for (j = 0; j < listChunk.getLength(); j++) {
                    Node nodeChunk = listChunk.item(j);
                    if (nodeChunk.getTextContent().equals(idChunk)) {
                        //chunk da co
                        System.out.println("da co");
                        break;
                    }

                }
                if (j == listChunk.getLength()) {
                    //chunk chua co, inser chunk
                    Node chunk = document.createElement("Chunk");
                    Node value = document.createTextNode(idChunk);
                    chunk.appendChild(value);
                    nodeFile.appendChild(chunk);
                    DOMUtil.writeXmlToFile("Data.xml", document);
                    System.out.println("add chunk" + idChunk + " cua file " + idFile);
                }

                break;
            }

        }
        if (i == listFile.getLength()) {
            //file chua co, inser file + chunk
            Element file = document.createElement("File");
            file.setAttribute("id", idFile);
            file.setAttribute("name", torrenFile.getName());
            file.setAttribute("size", String.format("%.0f", torrenFile.getSize() / 1024));
            file.setAttribute("chunk", Integer.toString(torrenFile.getChunks().size()));
            Node chunk = document.createElement("Chunk");
            Node value = document.createTextNode(idChunk);
            chunk.appendChild(value);
            file.appendChild(chunk);
            document.getDocumentElement().appendChild(file);
            DOMUtil.writeXmlToFile("Data.xml", document);
            System.out.println("add chunk" + idChunk + "va  add file " + idFile);
        }
    }

    public static void deleteChunk(String idFile, String idChunk) {
        Document document = DOMUtil.parse("Data.xml");
        NodeList listFile = document.getDocumentElement().getChildNodes();
        int i;
        for (i = 0; i < listFile.getLength(); i++) {
            Node nodeFile = listFile.item(i);
            if (nodeFile.getNodeName().equals("File") && nodeFile.getAttributes().getNamedItem("id").getNodeValue().equals(idFile)) {
                NodeList listChunk = nodeFile.getChildNodes();
                int j;
                for (j = 0; j < listChunk.getLength(); j++) {
                    Node nodeChunk = listChunk.item(j);
                    if (nodeChunk.getTextContent().equals(idChunk)) {
                        nodeFile.removeChild(nodeChunk);
                        DOMUtil.writeXmlToFile("Data.xml", document);
                        System.out.println("delete chunk " + idChunk + " file " + idFile);
                        break;
                    }

                }

                if (listChunk.getLength() == 0) {
                    document.getDocumentElement().removeChild(nodeFile);
                    DOMUtil.writeXmlToFile("Data.xml", document);
                    System.out.println("delete file " + idFile);
                }
            }
        }
 
   }

    public static void deleteFile(String idFile) {
        Document document = DOMUtil.parse("Data.xml");
        NodeList listFile = document.getDocumentElement().getChildNodes();
        int i;
        for (i = 0; i < listFile.getLength(); i++) {
            Node nodeFile = listFile.item(i);
            if (nodeFile.getNodeName().equals("File") && nodeFile.getAttributes().getNamedItem("id").getNodeValue().equals(idFile)) {

                document.getDocumentElement().removeChild(nodeFile);
                DOMUtil.writeXmlToFile("Data.xml", document);
                System.out.println("delete file " + idFile);
            }
        }
    }

    
/*
    public static void main(String[] ar) {
        Document document = DOMUtil.parse("Data.xml");
        //DOMUtil.printDOM(document);
        //insertChunk("123478", "1");
        //deleteChunk("123478", "6");
        deleteFile("123478");
        /*
       
    }*/
}
